package net.telesing.tcmc.back.logic;

import net.telesing.tcmc.back.dao.OrganizationDao;
import net.telesing.tcmc.back.dao.SectionDao;
import net.telesing.tcmc.back.model.OrgUserModel;
import net.telesing.tcmc.back.model.OrganizationModel;
import net.telesing.tcmc.back.model.SectionModel;
import net.telesing.tcmc.back.model.UserModel;
import net.telesing.tcmc.back.modelqp.OrganizationQp;
import net.telesing.tcmc.common.LogicException;
import net.telesing.tcmc.common.QueryReturn;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by bys on 2015/11/3.
 */
@IocBean
public class OrganizationLogic
{
    @Inject
    private OrganizationDao organizationDao;
    @Inject
    private SectionDao      sectionDao;
    @Inject
    private UserLogic       userLogic;

    private static final int UNKNOWN        = 0;
    private static final int LINK_NOT_FOUND = 1;
    private static final int REPEAT_ACCOUNT = 2;
    private static final int NOT_FOUND      = 3;

    private static final Logger log = LogManager.getLogger(OrganizationLogic.class);

    private LogicException error(int code)
    {
        switch (code)
        {
            case LINK_NOT_FOUND:
                return new LogicException(code, "组织机构代码重复");
            case REPEAT_ACCOUNT:
                return new LogicException(code, "机构名称已存在！");
            case NOT_FOUND:
                return new LogicException(code, "信息不存在");
            default:
                return new LogicException(code, "未知错误");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public OrganizationModel find(long id)
    {
        return organizationDao.fetch(id);
    }

    /**
     * 根据条件查询
     *
     * @param qp
     * @return
     */
    public QueryReturn doList(OrganizationQp qp,UserModel user)
    {
        if(user.getType() == 3){
        OrgUserModel orgUserModel = sectionDao.fetchIdModel(Cnd.where("UID","=",user.getId()));
        if (orgUserModel !=null){
            qp.setOrgId(orgUserModel.getOrgId());
        }
    }
        return organizationDao.queryPage(qp);
    }

    /**
     * 机构信息 新增 逻辑代码
     *
     * @param organization
     * @param creator
     * @return OrganizationModel
     * @throws LogicException
     */
    public OrganizationModel create(OrganizationModel organization, long creator) throws LogicException
    {
        Cnd aCnd = Cnd.where("ORG_CODE", "=", organization.getOrgCode()).and("STATUS","<>",0);
        Cnd cnd = Cnd.where("NAME", "=", organization.getName()).and("STATUS","<>",0);
        organization.setState(1);
        if (null != organizationDao.fetch(aCnd))
            throw error(LINK_NOT_FOUND);
        if (null != organizationDao.fetch(cnd))
            throw error(REPEAT_ACCOUNT);

        UserModel userModel = new UserModel();
        userModel.setName(organization.getUserName());
        if (!Strings.isEmpty(organization.getPwd()))
        {
            userModel.setPass(organization.getPwd());
        }
        else
        {
            userModel.setPass("888888");
        }
        userModel.setState(1);
        userModel.setType(3);
        UserModel user = userLogic.create(userModel, creator);

        OrganizationModel organizationModel = organizationDao.insert(organization, creator);
        if (user.getId() != 0 && organization.getId() != 0)
        {
            String sql = "INSERT INTO `tsc_org_user` (`hint`, `uid`, `oid`) VALUES ('', '" + user
                    .getId() + "', '" + organization.getId() + "')";
            organizationDao.touchSql(Sqls.create(sql));
        }
        return organizationModel;
    }

    /**
     * 机构信息 编辑 逻辑代码
     *
     * @param organization
     * @param updater
     * @return
     * @throws LogicException
     */
    public int modify(OrganizationModel organization, long updater) throws LogicException
    {
        OrganizationModel organizationModel = organizationDao.fetch(organization.getId());
        if (organization.getState() == 0)
        {
            organization.setState(organizationModel.getState());
        }

        if (!organizationModel.getOrgCode().equals(organization.getOrgCode()))
        {
            Cnd aCnd = Cnd.where("ORG_CODE", "=", organization.getOrgCode()).and("STATUS","<>",0);
            if (null != organizationDao.fetch(aCnd))
                throw error(LINK_NOT_FOUND);
        }
        if (!organizationModel.getName().equals(organization.getName()))
        {
            Cnd cnd = Cnd.where("NAME", "=", organization.getName()).and("STATUS","<>",0);
            if (null != organizationDao.fetch(cnd))
                throw error(REPEAT_ACCOUNT);
        }

        UserModel userModel = userLogic.find(organization.getUserId());
        userModel.setName(organization.getUserName());
        userModel.setState(1);
        userModel.setType(3);
        if (!Strings.isEmpty(organization.getPwd()))
        {
            userModel.setPass(organization.getPwd());
        }else {
            userModel.setPass(null);
        }
        userLogic.modify(userModel, updater);

        return organizationDao.update(organization, updater);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @throws LogicException
     */
    public void delete(long[] ids, long updater) throws LogicException
    {
        if (ids.length != 0)
        {
            try
            {
                Cnd cnd = Cnd.where("ID", "=", ids[0]);
                Cnd cndList = Cnd.where("OID", "=", ids[0]);

                String sql = "update tsc_organization set  status=0,upt_user =" + updater + " $condition";
                String sql1 = "DELETE FROM tsc_section  $condition";//删除字表
                String sql2 = "DELETE FROM tsc_certificate  $condition";//删除字表
                String sql3 = "update tsc_user set STATE = 0,upt_user =" + updater + " where ID in (select uid from tsc_org_user $condition )";//用户作废

                List<SectionModel> sectionModelList = sectionDao.fetchList(SectionModel.class, cndList);

                if (sectionModelList.size() != 0)
                {
                    Cnd aCnd = Cnd.where("SID", "=", sectionModelList.get(0).getId());
                    Cnd bCnd = Cnd.where("ID", "=", sectionModelList.get(0).getId());
                    for (int i = 1; i < sectionModelList.size(); i++)
                    {
                        aCnd = aCnd.or("SID", "=", sectionModelList.get(i).getId());
                        bCnd = bCnd.or("ID", "=", sectionModelList.get(i).getId());
                    }
                    organizationDao.touchSql(Sqls.create(sql2).setCondition(aCnd));
                    organizationDao.touchSql(Sqls.create(sql1).setCondition(bCnd));
                }
                organizationDao.touchSql(Sqls.create(sql).setCondition(cnd));
                organizationDao.touchSql(Sqls.create(sql3).setCondition(cndList));
            }
            catch (Exception e)
            {
                e.printStackTrace();
                throw error(UNKNOWN);
            }
        }
    }

    public String getJsp(int flg)
    {
        String result;
        if (flg == 1){
            result = "pages.back.organization.org_table";
        }else if (flg == 2){
            result = "pages.back.section.select_org";
        }else
            result = "pages.back.organization.organization";
        return result;
    }
}
